//
//  NewsDetailViewController.m
//  xinhua_sx
//
//  Created by 党阳阳 on 14-5-26.
//  Copyright (c) 2014年 dangyangyang. All rights reserved.
//

#import "NewsDetailViewController.h"
#import "ReactiveCocoa.h"
#import "MBProgressHUD.h"
#import <QuartzCore/QuartzCore.h>
#import "NewsDetailViewModel.h"
#import <shareSDK/ShareSDK.h>




@interface NewsDetailViewController ()
@property (nonatomic ,strong) MBProgressHUD *HUD;
@property (nonatomic ,strong) UIWebView *webView;
@property (nonatomic ,strong) id newsId;
@property (nonatomic ,strong) NewsDetailViewModel *viewModel;


@end

@implementation NewsDetailViewController
@synthesize imageString = _imageString;
@synthesize fefncode = _fefncode;
- (id)initWithNewsId:(id)newsId
{
    self = [self init];
    if (self) {
        _viewModel = [[NewsDetailViewModel alloc]initWithNewsId:newsId];
        NSLog(@"newid = %@",newsId);
        _newsId = newsId;
        [_webView loadRequest:[NSURLRequest requestWithURL:[self.viewModel getNewsURL]]];
        butoncl* al = [[butoncl alloc] init];
        NSString* fff = [NSString stringWithFormat:@"%@",newsId];
        NSLog(@"fff = %@",fff);
        [al postString:@"004"fff:fff];
        
        
    }
    return self;
}

- (id)init
{
    self = [super init];
    if (self) {
        // Custom initialization
        self.view.frame = [[UIScreen mainScreen]bounds];
        [self.leftButton setImage:[UIImage imageNamed:@"icon_back@2x.png"] forState:UIControlStateNormal];
        
        @weakify(self);
        [[self.leftButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self);
            [self.navigationController popViewControllerAnimated:YES];
        }];
    
       
        [self.rightButton setImage:[UIImage imageNamed:@"news_detail_share.png"] forState:UIControlStateNormal];
        [[self.rightButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id sender) {
           // 右键分享
//            @strongify(self);
            NSString *titleJS = @"document.title";
            NSString *titleString = [_webView stringByEvaluatingJavaScriptFromString:titleJS];
            
            
           
            
          //  NSString *titleJS = @"document.title";
           // NSString *titleString = [_webView stringByEvaluatingJavaScriptFromString:titleJS];
            
            
           // NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"ShareSDK"  ofType:@"jpg"];
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
            // 当前应用名称
            NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
            NSLog(@"当前应用名称：%@",appCurName);

            NSArray *shareList = [ShareSDK getShareListWithType:ShareTypeQQSpace, ShareTypeTencentWeibo,ShareTypeSinaWeibo, nil];
            //构造分享内容
            NSString*fff ;
            if ([_fefncode length] <= 0)
            {
                fff = COUTURYCODE;
            }
            else
                fff = _fefncode;
            NSString* sf = [NSString stringWithFormat:@"%s/xinhua/f/mobileAdView-%@.html?officeCode=%@",HTTP,_newsId,COUTURYCODE];
            NSLog(@"ur = %@",sf);
            id<ISSContent> publishContent = [ShareSDK content:[NSString stringWithFormat:@"《%@》详情请点击%@",titleString,sf]
                                               defaultContent:appCurName
                                                        image:[ShareSDK imageWithUrl:_imageString]
                                                        title:titleString
                                                          url:sf
                                                  description:@""
                                                    mediaType:SSPublishContentMediaTypeNews];
            
            [ShareSDK showShareActionSheet:nil
                                 shareList:nil
                                   content:publishContent
                             statusBarTips:YES
                               authOptions:nil
                              shareOptions: nil
                                    result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                        if (state == SSResponseStateSuccess)
                                        {
                                                                                        NSLog(@"分享成功");
                                        }
                                        else if (state == SSResponseStateFail)
                                        {
                                                                                        NSLog(@"分享失败,错误码:%d,错误描述:%@", [error errorCode], [error errorDescription]);
                                        }
                                        butoncl* al = [[butoncl alloc] init];
                                        [al postString:@"008" fff:@""];
                                    }];
            

            
//            id<ISSContent> publishContent = [ShareSDK content:[NSString stringWithFormat:@"《%@》详情请点击%@",titleString,[_webView.request.URL absoluteString]]
//                                               defaultContent:@"掌上晋源"
//                                                        image:[ShareSDK imageWithPath:imagePath]
//                                                        title:titleString
//                                                          url:[_webView.request.URL absoluteString]
//                                                  description:@"这是一条测试信息"
//                                                    mediaType:SSPublishContentMediaTypeNews];
//            
//            [ShareSDK showShareActionSheet:nil
//                                 shareList:nil
//                                   content:publishContent
//                             statusBarTips:YES
//                               authOptions:nil
//                              shareOptions: nil
//                                    result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
//                                        if (state == SSResponseStateSuccess)
//                                        {
////                                            NSLog(@"分享成功");
//                                        }
//                                        else if (state == SSResponseStateFail)
//                                        {
////                                            NSLog(@"分享失败,错误码:%d,错误描述:%@", [error errorCode], [error errorDescription]);
//                                        }
//                                    }];
//            
           
            
        }];

        
        _webView =[[UIWebView alloc] initWithFrame:CGRectMake(0, self.navBar.frame.size.height, self.view.frame.size.width, self.view.frame.size.height-self.navBar.frame.size.height-40)];
        for (UIView *subView in [_webView subviews]) {
            if ([subView isKindOfClass:[UIScrollView class]]) {
                UIScrollView *scrollView =  (UIScrollView *)subView;
                scrollView.bounces = NO;
                scrollView.showsHorizontalScrollIndicator = NO;
                scrollView.showsVerticalScrollIndicator = NO;
            }
        }
        _webView.delegate = self;

        [self.view addSubview:_webView];
        
        UIView *bottome = [[UIView alloc] initWithFrame:CGRectMake(0, _webView.frame.size.height+_webView.frame.origin.y, 320, 40)];
    
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 1.0)];
        line.backgroundColor = [UIColor grayColor];
        [bottome addSubview:line];
        
        
        bottome.backgroundColor = [UIColor whiteColor];
        UIButton *praiseButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, 30, 30)];
        [praiseButton setImage:[UIImage imageNamed:@"news_detail_praise.png"] forState:UIControlStateNormal
         ];
        [praiseButton setImage:[UIImage imageNamed:@"news_detail_praise_selected.png"] forState:UIControlStateSelected];
        
        [[praiseButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id sender) {
            
            // 点赞
            [self praiseNews:sender];
            
        }];
        
        [bottome addSubview:praiseButton];
        
        UIButton *attentButton = [[UIButton alloc] initWithFrame:CGRectMake(40, 5, 30, 30)];
        [attentButton setBackgroundImage:[UIImage imageNamed:@"news_detail_attention.png"] forState:UIControlStateNormal];
        [attentButton setBackgroundImage:[UIImage imageNamed:@"news_detail_attention_selected.png"] forState:UIControlStateSelected];
        
        [[attentButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id sender) {
            // 收藏新闻
            [self attentionNews:sender];
            
                    }];
        
        [bottome addSubview:attentButton];
        
        UIButton *sendButton = [[UIButton alloc] initWithFrame:CGRectMake(260, 5, 50, 30)];
        sendButton.backgroundColor = [UIColor colorWithRed:71.0/255 green:153.0/255 blue:211.0/255 alpha:1.0];
        [sendButton setTitle:@"发表" forState:UIControlStateNormal];
        [sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        sendButton.layer.cornerRadius = 5.0f;
        sendButton.layer.masksToBounds = YES;
        [[sendButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            // 发表评论
            
            
        }];
        [bottome addSubview:sendButton];
        
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(80, 5, 160, 30)];
        textField.placeholder = @"评论...";
        textField.layer.cornerRadius = 5.0f;
        textField.layer.masksToBounds = YES;
        [bottome addSubview:textField];
        textField.userInteractionEnabled = NO;
        
        [self.view addSubview:bottome];
        
        UISwipeGestureRecognizer *swip = [[UISwipeGestureRecognizer alloc] init];
        [self.view addGestureRecognizer:swip];
        swip.direction = UISwipeGestureRecognizerDirectionRight;
        [[swip rac_gestureSignal] subscribeNext:^(id x) {
           
            [self.navigationController popViewControllerAnimated:YES];
        }];
        
        _HUD = [[MBProgressHUD alloc] initWithView:self.view];
        _HUD.labelText = @"加载数据";
        [self.view addSubview:_HUD];
        
        
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.userInteractionEnabled = YES;
   
   
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)popMyself:(id)sender
{
    
    [self.navigationController popViewControllerAnimated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark webView Delegate

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    
    [_HUD show:YES];
    
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [_HUD hide:YES];
   
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
   
    UIAlertView *aletView = [[UIAlertView alloc] initWithTitle:@"请求失败" message:@"网络出现错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
    [aletView show];
    
    
}

- (void)alertViewCancel:(UIAlertView *)alertView
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark 收藏新闻
//  判断用户是否登录，如已经登录方可进行操作

- (void)attentionNews:(id)sender
{
    
    MBProgressHUD* HUD = [[MBProgressHUD alloc] initWithView:self.view];
    
    [self.view addSubview:HUD];

    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    id UID = [defaults objectForKey:@"UID"];
    
    if (!UID) {
        HUD.labelText = @"请先登录";
        [HUD showAnimated:YES whileExecutingBlock:^{
            sleep(1);
        } completionBlock:^{
            [HUD removeFromSuperview];
        }];
        return;
    }
    UIButton *button = (UIButton *)sender;
    if (button.selected) {
        NSLog(@"222");
        [[self.viewModel deleteAttentionNewsWithUserId:UID NewsId:_newsId] subscribeNext:^(id data) {
            if ([data isKindOfClass:[NSString class]]) {
                [self performSelectorOnMainThread:@selector(showMessage:) withObject:data waitUntilDone:NO];
            }
            if ( [data isKindOfClass:[NSDictionary class]]) {
                [self performSelectorOnMainThread:@selector(showMessage:) withObject:[data objectForKey:@"message"] waitUntilDone:NO];
                [self performSelectorOnMainThread:@selector(setButtonState:) withObject:button waitUntilDone:NO];
            }
            butoncl* al = [[butoncl alloc] init];
            [al postString:@"006"fff:@""];
        }];
        
        
    }else{
        
        NSLog(@"333");
        NSLog(@"nesid = %@",_newsId);
        [[self.viewModel attentionNewsWithUserId:UID NewsId:_newsId] subscribeNext:^(id data) {
            if ([data isKindOfClass:[NSString class]]) {
                [self performSelectorOnMainThread:@selector(showMessage:) withObject:data waitUntilDone:NO];
            }
            if ( [data isKindOfClass:[NSDictionary class]]) {
                [self performSelectorOnMainThread:@selector(showMessage:) withObject:[data objectForKey:@"message"] waitUntilDone:NO];
                [self performSelectorOnMainThread:@selector(setButtonState:) withObject:button waitUntilDone:NO];
            }
            butoncl* al = [[butoncl alloc] init];
            [al postString:@"005"fff:@""];
            
        }];
        
        
        
        return ;
    }

}

#pragma mark 点赞 

- (void)praiseNews:(id)sender
{
    
    MBProgressHUD* HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];

    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    id UID = [defaults objectForKey:@"UID"];
    
    if (!UID) {
        HUD.labelText = @"请先登录";
        [HUD showAnimated:YES whileExecutingBlock:^{
            sleep(1);
        } completionBlock:^{
            [HUD removeFromSuperview];
        }];
        return;
    }
    
    UIButton *button = (UIButton *)sender;
    if (button.selected) {
         HUD.labelText = @"您已经点过赞了";
        [HUD showAnimated:YES whileExecutingBlock:^{
            sleep(1);
        } completionBlock:^{
            [HUD removeFromSuperview];
        }];
        
        return ;
        
        
    }
    
    // 点赞
    
    [[self.viewModel praiseNewsWitdUserId:UID NewsId:_newsId]subscribeNext:^(id data) {
        
        if ([data isKindOfClass:[NSString class]]) {
            [self performSelectorOnMainThread:@selector(showMessage:) withObject:data waitUntilDone:NO];
        }
        if ( [data isKindOfClass:[NSDictionary class]]) {
            [self performSelectorOnMainThread:@selector(showMessage:) withObject:[data objectForKey:@"message"] waitUntilDone:NO];
            [self performSelectorOnMainThread:@selector(setButtonState:) withObject:button waitUntilDone:NO];
        }
        butoncl* al = [[butoncl alloc] init];
        [al postString:@"011"fff:@""];
    }];

    
        
}

#pragma mark 提示信息
- (void)showMessage:(NSString *)message
{
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.labelText = message;
    [self.view addSubview:HUD];
    [HUD showAnimated:YES
  whileExecutingBlock:^{
      sleep(1);
  }
      completionBlock:^{
          [HUD removeFromSuperview];
      }];
    
}

// 改变button状态
- (void)setButtonState:(id)sender
{
    if ([sender isKindOfClass:[UIButton class]]) {
        UIButton *button = (UIButton *)sender;
        button.selected = !button.selected;
    }
}


@end
